package com.yuntoyun.codeavatar.app.activity.main;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Message;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.PagerAdapter;

import com.flyco.tablayout.listener.CustomTabEntity;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.yuntoyun.codeavatar.app.R;
import com.yuntoyun.codeavatar.app.fwcore.core.AppCoreSign;
import com.yuntoyun.fwcore.appext.data.AppData;
import com.yuntoyun.fwcore.appext.data.AppPathData;
import com.yuntoyun.fwcore.base.FwBaseViewPagerNavActivity;
import com.yuntoyun.fwcore.base.entity.FwViewPagerNavEntity;
import com.yuntoyun.fwcore.model.FwResultJsonDataModel;
import com.yuntoyun.fwcore.model.FwResultJsonListDataModel;
import com.yuntoyun.fwcore.plug.network.retrofit.FwOkHttp;
import com.yuntoyun.fwcore.util.FwAlertDialogUtil;
import com.yuntoyun.fwcore.util.FwAppUtil;
import com.yuntoyun.fwcore.util.FwApplicationUtil;
import com.yuntoyun.fwcore.util.FwGsonUtil;
import com.yuntoyun.fwcore.util.FwLogUtil;
import com.yuntoyun.fwcore.util.FwToastUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.observers.DisposableObserver;

public class MainActivity extends FwBaseViewPagerNavActivity {

    private final String fTag = MainActivity.class.getSimpleName();

    private final int gActionUpgrade = 901;

    //设置广播
    public static final String ACTION_APP_EXIT = "app.exit";
    public static final String PERMISSION_APP_EXIT = "com.yuntoyun.fwcore.app.exit";

    @BindView(R.id.llt_upgrade)
    LinearLayout llt_upgrade;
    @BindView(R.id.pbr_progress)
    ProgressBar pbr_progress;
    @BindView(R.id.tvw_text)
    TextView tvw_text;
    @BindView(R.id.tvw_upgrade_title)
    TextView tvw_upgrade_title;
    @BindView(R.id.tvw_upgrade_option)
    TextView tvw_upgrade_option;


    private long gExitTime;
    private int gClickBackNum = 2; //返回按扭限制点击数量

    private ArrayList<Fragment> gTabFragments;
    private ArrayList<CustomTabEntity> gTabEntities;

    /////////
    ///升级变量
    /////////
    private String mVersion = "";
    //升级变量
    private String mHttpApk = "";
    private String mTargetApk = "";
    private boolean mRan = true;
    private boolean mInstall = false;
    //8.0以上安装必须签名
    private String mApkName = "ZPH_Personal.apk";
    private String mApkHttpUrl, mMustUpgrade, mNewVersion;

    private final int mRCodeInstall = 110;
    private final int mRCodeStorage = 111;
    private final int mSCodeInstall = 112;
    private final int mSCodeStoreage = 114;

    //实例
    private static MainActivity instance = null;

    @Override
    protected ArrayList<Fragment> getTabFragments() {
        return gTabFragments;
    }

    @Override
    protected ArrayList<CustomTabEntity> getTabEntities() {
        return gTabEntities;
    }

    @Override
    protected PagerAdapter getPagerAdapter(FragmentManager fragmentManager) {
        return new FragmentPagerAdapter(fragmentManager) {
            @Override
            public Fragment getItem(int position) {
                return gTabFragments.get(position);
            }

            @Override
            public int getCount() {
                return gTabFragments.size();
            }
        };
        //FragmentStatePagerAdapter(无缓存显示)
    }

    @Override
    protected int initChildLayoutResId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initChildView() {
        instance = this;
        //注册广播
        IntentFilter filter = new IntentFilter();
        filter.addAction(ACTION_APP_EXIT);
        registerReceiver(receiver, filter, PERMISSION_APP_EXIT, null);
        //当前版本
        mVersion = FwApplicationUtil.builder().getAppVersionName();
    }

    @Override
    protected void initChildData() {
        //检测升级
        this.checkVersion();
    }

    @Override
    protected void initChildEvent() {

    }

    @Override
    protected void beforeLayout() {
        if (null == this.gTabFragments) {
            //隐藏状态栏
//            FwBarUtil.setNavBarVisibility(this, false);

            //加载导航页面
            this.gTabFragments = new ArrayList<>();
            this.gTabFragments.add(new HomeFragment());
            this.gTabFragments.add(new AgricultureFragment());
            if (AppData.isAppTaskSwitch()) {
                this.gTabFragments.add(new TaskFragment());
            }
            this.gTabFragments.add(new OwnerFragment());
            //加载导航数据
            this.gTabEntities = new ArrayList<>();
            this.gTabEntities.add(new FwViewPagerNavEntity("首页", R.mipmap.icon_nav_home_checked,
                    R.mipmap.icon_nav_home_unchecked));
            this.gTabEntities.add(new FwViewPagerNavEntity("助农", R.mipmap.icon_nav_agriculture_checked,
                    R.mipmap.icon_nav_agriculture_unchecked));
            if (AppData.isAppTaskSwitch()) {
                this.gTabEntities.add(new FwViewPagerNavEntity("任务", R.mipmap.icon_nav_task_checked,
                        R.mipmap.icon_nav_task_unchecked));
            }
            this.gTabEntities.add(new FwViewPagerNavEntity("我的", R.mipmap.icon_nav_owner_checked,
                    R.mipmap.icon_nav_owner_unchecked));
        }
    }

    @Override
    protected void initNavigation() {

    }

    @Override
    protected void messageHandler(Message msg) {

    }

    @Override
    protected void messageHandler(FwResultJsonDataModel model) {
        if (gActionUpgrade == model.getIndex()) {
            JsonObject tmpData = model.getFwData();
            mNewVersion = FwGsonUtil.builder().getString(tmpData, "newVersion");
            mApkHttpUrl = FwGsonUtil.builder().getString(tmpData, "downloadApk");
            mMustUpgrade = FwGsonUtil.builder().getString(tmpData, "mustUpgrade");
            tvw_upgrade_title.setText(fwGsonUtil.getString(tmpData, "title"));
            StringBuffer sb = new StringBuffer("");
            JsonArray jarr = fwGsonUtil.getJsonArray(tmpData, "descrpiton");
            for (int i = 0; i < jarr.size(); i++) {
                if (i > 0) {
                    sb.append("\n");
                }
                sb.append(jarr.get(i).getAsString());
            }
            tvw_upgrade_option.setText(sb.toString());
            doUpgradeTip();
        }
    }

    @Override
    protected void messageHandler(FwResultJsonListDataModel model) {

    }

    @Override
    public void onClick(View v) {

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case mRCodeInstall:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    if (ActivityCompat.checkSelfPermission(this, Manifest.permission
                            .WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                        this.doUpgradeTip();
                    } else {
                        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission
                                .WRITE_EXTERNAL_STORAGE}, mRCodeStorage);
                    }
                } else {
                    FwToastUtil.builder().makeText("请开启安装未知应用权限！");
                    Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
                    startActivityForResult(intent, mSCodeInstall);
                }
                break;
            case mRCodeStorage:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    this.checkVersion();
                } else {
                    FwToastUtil.builder().makeText("请开启存储权限！");
                    Intent intent = new Intent(Settings.ACTION_INTERNAL_STORAGE_SETTINGS);
                    startActivityForResult(intent, mSCodeStoreage);
                }
                break;
        }
    }

    @Override
    public void onBackPressed() {
        if (mInstall) {
            FwToastUtil.builder().makeText("升级中...");
        } else {
            long currentTimeMillis = System.currentTimeMillis();

            //单位为毫秒
            if ((currentTimeMillis - gExitTime) < 3000) {
                FwToastUtil.builder().makeText("二次连击退出应用!");
                gClickBackNum -= 1;
                if (0 == gClickBackNum) {
//                System.exit(0);
                    finish();
                }
            } else {
                gExitTime = currentTimeMillis;
                gClickBackNum = 2;
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        instance = null;
        //卸载广播
        unregisterReceiver(receiver);
        super.onDestroy();
    }

    //=================================================================

    public void switchTabs(int idx) {
        if (idx >= vpr_pages.getChildCount()) return;

        //必须在主线程中运行
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                vpr_pages.setCurrentItem(idx, true);
            }
        });
    }

    public void switchTabs(int idx, boolean isRefresh) {
        switchTabs(idx);
        if (isRefresh) {
            refreshTab(idx);
        }
    }

    public void refreshNavTask() {
        if (AppData.isAppTaskSwitch()) {
            refreshTab(2);
        }
    }

    public void refreshNavOwner() {
        refreshTab(gTabFragments.size() - 1);
    }

    public void refreshTab(int idx) {
        if (idx >= gTabFragments.size()) return;

        //必须在主线程中运行
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Fragment tmpFragment = gTabFragments.get(idx);
                if (tmpFragment instanceof HomeFragment) {
                    //同步刷新
                    ((HomeFragment) tmpFragment).doReloadData();
                } else if (tmpFragment instanceof TaskFragment) {
                    //同步刷新
                    ((TaskFragment) tmpFragment).reloadData();
                } else if (tmpFragment instanceof OwnerFragment) {
                    //同步刷新
                    ((OwnerFragment) tmpFragment).reloadData();
                }
            }
        });
    }

    public List<DisposableObserver> getFwObserverList() {
        return fwObserverList;
    }

    public static MainActivity getInstance() {
        return instance;
    }

    //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction() == ACTION_APP_EXIT) {
                fwActivity.finish();
            }
        }
    };

    //////////
    ///检测升级
    //////////

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        FwLogUtil.info(this.fTag, "The onActivityResult event is ran.");

        switch (requestCode) {
            case mSCodeInstall:
                if ("yes".equals(mNewVersion)) {
                    doUpgradeTip();
                }
                break;
            case mSCodeStoreage:
                if (resultCode == RESULT_OK) {
                    doUpgradeTip();
                }
                break;
            default:
                if (RESULT_OK == resultCode) {
                    int idx = vpr_pages.getCurrentItem();
                    this.gTabFragments.get(idx).onActivityResult(requestCode, resultCode, data);
                }
                break;
        }
    }

    private void doUpgradeTip() {
        //是否有新版本，选项：no》否；yes》是；
        if ("yes".equals(mNewVersion)) {
            FwAlertDialogUtil.builder().showCustomConfirmDialog(this, "检测升级",
                    "升级到最新版本！", "暂不升级", "我要升级", new FwAlertDialogUtil
                            .CustomClickListener() {


                        @Override
                        public void clickPositiveButton(DialogInterface dialog) {
                            //提交逻辑
                            doCheckPermission();
                        }

                        @Override
                        public void clickNegativeButton(DialogInterface dialog) {
                            //取消逻辑

                            //是否强制升级，yes:是；no:否
                            if ("yes".equals(mMustUpgrade)) {
                                finish();
                            }
                        }
                    });
        }
    }

    private void doCheckPermission() {
        if (Build.VERSION.SDK_INT >= 26) {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission
                    .WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                if (getPackageManager().canRequestPackageInstalls()) {
                    this.doUpgrade();
                } else {
                    ActivityCompat.requestPermissions(this,
                            new String[]{Manifest.permission.REQUEST_INSTALL_PACKAGES}, mRCodeInstall);
                }
            } else {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission
                        .WRITE_EXTERNAL_STORAGE}, mRCodeStorage);
            }
        } else if (Build.VERSION.SDK_INT >= 24) {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission
                    .WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                this.doUpgrade();
            } else {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission
                        .WRITE_EXTERNAL_STORAGE}, mRCodeStorage);
            }
        } else {
            this.doUpgrade();
        }
    }

    //升级代码

    private void checkVersion() {
        HashMap<String, Object> map = new HashMap<>();
        map.put("version", mVersion);
        AppCoreSign.addSign(map);
        Observable<FwResultJsonDataModel> observable = FwOkHttp.getFwAPIService()
                .getAppUpgrade(map);
        super.doPostData(gActionUpgrade, observable, false);
    }

    private void doUpgrade() {
        if (!TextUtils.isEmpty(mApkHttpUrl)) {
            llt_upgrade.setVisibility(View.VISIBLE);
            mInstall = true; //升级标识

            this.mTargetApk = AppPathData.init().getApkPath() + mApkName;
            this.mHttpApk = mApkHttpUrl;
            this.startLoad();
        } else {
            FwToastUtil.builder().makeText("APK在线地址错误！");
        }
    }

    private void startLoad() {
        // 设置按钮内容 ----并没有用...
        pbr_progress.setIndeterminate(false);

        new Thread(new Runnable() {
            private int percent;

            @Override
            public void run() {
                try {
                    // 打开 URL 必须在子线程
                    URL url = new URL(mHttpApk);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();//HTTP URL链接
                    conn.setRequestMethod("GET");
                    conn.setReadTimeout(5000);
                    conn.setConnectTimeout(5000);

                    int contentLength = conn.getContentLength();//获取内容长度

                    if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {//如果获取相应代码成功

                        final InputStream is = conn.getInputStream();

                        final File file = new File(mTargetApk);
                        if (!file.exists()) {
                            file.createNewFile();
                        }

                        final FileOutputStream fileOut = new FileOutputStream(file);
                        byte[] buffer = new byte[1024 * 1024 * 10];
                        int len = -1;
                        int sum = 0;
                        while ((len = is.read(buffer)) != -1) {
                            sum += len;
                            // 注意强转方式，防止一直为0
                            percent = (int) (100.0 * sum / contentLength);

                            fileOut.write(buffer, 0, len);

                            // 在主线程上运行的子线程
                            runOnUiThread(new Runnable() {

                                @Override
                                public void run() {

                                    pbr_progress.setProgress(percent);
                                    tvw_text.setText(percent + "%");

                                    if (percent >= pbr_progress.getMax()) {
                                        try {
                                            if (mRan) {
                                                mRan = false;
                                                fileOut.flush();
                                                installApk(file);
                                            }
                                        } catch (IOException e) {
                                            FwLogUtil.error(fTag, e);
                                        }
                                    }
                                }

                            });
                        }

                        is.close();
                        conn.disconnect();
                    }
                } catch (IOException e) {
                    FwLogUtil.error(fTag, e);
                }
            }

        }).start();

    }

    private void installApk(File file) {
        if (null == file) {
            file = new File(mTargetApk);
        }
        //开始安装
        FwAppUtil.installApp(file);
        mInstall = false;
        llt_upgrade.setVisibility(View.GONE);
    }


}
